﻿package hapi.db;
import haxe.Timer;
#if php
import php.db.Connection;
import php.Lib;
#else neko
import neko.db.Connection;
import neko.Lib;
#end

typedef DBRequest = {
	var query:String;
	var duration:Float;
}

class DebuggConnection implements Connection {

	var conn:Connection;
	var requests:List<DBRequest>;
	public var totalDuration(default,null):Float;
	
	public function new(conn) {
		this.conn = conn;
		this.requests = new List<DBRequest>();
		this.totalDuration = 0.;
	}
	
	public function addValue( s : StringBuf, v : Dynamic ) : Void {
		conn.addValue(s, v);
	}
	
	private function addRequest(s, duration) {
		this.requests.add( { query:s, duration:duration } );
		this.totalDuration += duration;
	}
	
	public function request( s : String ) {
		var time = Timer.stamp();
		var error = null;
		var result = null;
		try {
			result = conn.request(s);
		}catch (e:Dynamic) {
			error = e;
		}
		var duration = (Timer.stamp() - time)*1000.;
		addRequest(s, duration);
		if ( error != null ) Lib.rethrow(error);
		return result;
	}
	public function close() : Void {
		return conn.close();
	}
	public function escape( s : String ) : String {
		return conn.escape(s);
	}
	public function quote( s : String ) : String {
		return conn.quote(s);
	}
	public function lastInsertId() : Int {
		return conn.lastInsertId();
	}
	public function dbName() : String {
		return conn.dbName();
	}
	public function startTransaction() : Void {
		conn.startTransaction();
	}
	public function commit() : Void {
		conn.commit();
	}
	public function rollback() : Void {
		conn.rollback();
	}
	
	public function requestsToString() {
		var buf = new StringBuf();
		var time = 0.;
		for ( r in requests ) {
			buf.add( "["+r.duration+"] " + r.query + "\n");
		}
		buf.add("Total: " + this.totalDuration + "--------------------------------------\n");
		return buf.toString();
	}
}